package icu.cocoon.sms.service.impl;


import com.aliyuncs.exceptions.ClientException;
import com.fasterxml.jackson.core.JsonProcessingException;
import icu.cocoon.security.service.VerificationCodeService;
import icu.cocoon.sms.service.SmsService;
import java.util.concurrent.TimeUnit;
import javax.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

/**
 * @author xce
 * @date 2020/3/19  16:39
 */
@Service
@Slf4j
public class VerificationCodeServiceImpl implements VerificationCodeService {

  @Resource
  private SmsService smsService;

  @Resource
  private RedisTemplate<String, String> redisTemplate;

  private final static String SMS_CODE_PREFIX = "sms_code";

  @Override
  public void sendVerificationCode(String address, String code) {
    try {
      log.info("发送目标:{},Code:{}", address, code);
      smsService.sendSmsCode(address, code);
      String key = SMS_CODE_PREFIX + address;
      redisTemplate.opsForValue().set(key, code, 120, TimeUnit.SECONDS);
    } catch (ClientException | JsonProcessingException e) {
      e.printStackTrace();
      log.error("短信验证码发送失败 Message：{}" + e.getMessage());
    }
  }

  @Override
  public boolean verify(String address, String userCode) {
    String key = SMS_CODE_PREFIX + address;
    String code = redisTemplate.opsForValue().get(key);
    return StringUtils.equals(userCode, code);
  }
}
